	import { weChatMiniProgramLogin } from '@/api/common/login'
	import { loginSuccess } from '@/hooks/login'
	export default {
		data() {
			return {
				// 微信临时登录凭证
				code: '',
			}
		},
		methods: {
			goBack(){
				uni.navigateBack({
				    delta: 1
				});
			},
			getCode() {
				return new Promise((resolve, reject) => {
					uni.login({
						success: (res) => {
							if (res.errMsg == "login:ok") {
								this.code = res.code;
								resolve(res.code)
							} else {
								uni.showToast({
									title: '系统异常，请联系管理员!'
								})
								reject()
							}
						}
					})
				})
			},
			showToastError(error){
				uni.showToast({
					title: '登录失败' + error,
					mask: true,
					icon: 'none'
				})
			},
			//微信授权登录
			getUserInfo(e) {
				if (!this.agreed) {
				  return this.showToast('请先同意用户协议和隐私政策');
				}
				let that = this;
				uni.showLoading({title: '登录中...',mask: true})
				var p = this.getSetting();
				p.then(function(isAuth) {
					console.log('是否已经授权', isAuth);
					if (isAuth) {
						console.log('用户信息，加密数据', e);
						//eData  包括//微信头像//微信名称 还有加密的数据.
						let eData = JSON.parse(e.detail.rawData);

						const submitObj = {
							code: that.code,
							nickName: eData.nickName,
							avatarUrl: eData.avatarUrl
						}
						weChatMiniProgramLogin(submitObj).then(res => {
							if(res?.token?.length == 0){
								that.showToastError()
								return
							}
							loginSuccess(res.token)
							uni.hideLoading();
						}).catch(error => {
							that.showToastError(error)
							uni.hideLoading();
						})
					} else {
						uni.showToast({
							title: '授权失败，请确认授权已开启',
							mask: true,
							icon: 'none'
						})
						uni.hideLoading();
					}
				}).catch(e => {
					console.log('获取授权失败', e);
					uni.hideLoading();
				})
			},
			//获取用户的当前设置
			getSetting() {
				return new Promise(function(resolve, reject) {
					uni.getSetting({
						success: function(res) {
							if (res.authSetting['scope.userInfo']) {
								resolve(true);
							} else {
								resolve(false);
							}
						},
						fail: (err) => {
							console.error('获取设置失败:', err);
							reject(err);  // 在失败时调用 reject
						}
					})
				}).catch((e) => {
					console.log(e)
				})
			},
		},
		onLoad() {
			this.getCode()
		}
	}